package com.deyou.activity;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.deyou.Constants;
import com.deyou.DeYouApplication;
import com.deyou.R;
import com.deyou.base.BaseActivity;
import com.deyou.callback.ServerApi;
import com.deyou.fragment.HouseBookInfoFragment;
import com.deyou.model.HouseResourceDetailBean;
import com.deyou.model.LzyResponse;
import com.deyou.model.SimpleResponse;
import com.deyou.util.AESUtil;
import com.deyou.util.AMapUtil;
import com.deyou.util.AndroidUtils;
import com.deyou.util.DensityUtils;
import com.deyou.util.GlideImageLoader;
import com.deyou.util.SPUtils;
import com.deyou.util.Urls;
import com.deyou.widget.CircleImageView;
import com.deyou.widget.ExpandableTextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.zhy.autolayout.utils.DimenUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class HouseResourceDetailActivity extends BaseActivity implements GeocodeSearch.OnGeocodeSearchListener {

    @BindView(R.id.iv_left_back)
    ImageView ivLeftBack;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.tv_mid_title)
    TextView tvMidTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.house_img_banner)
    Banner houseImgBanner;
    @BindView(R.id.iv_collect)
    ImageView ivCollect;
    @BindView(R.id.iv_house_owner)
    CircleImageView ivHouseOwner;
    @BindView(R.id.tv_house_owner)
    TextView tvHouseOwner;
    @BindView(R.id.house_owner_info_layout)
    LinearLayout houseOwnerInfoLayout;
    @BindView(R.id.tv_house_address)
    TextView tvHouseAddress;
    @BindView(R.id.tv_rent_mode)
    TextView tvRentMode;
    @BindView(R.id.house_rent_mode_layout)
    LinearLayout houseRentModeLayout;
    //    @BindView(R.id.tv_house_intro)
//    TextView tvHouseIntro;
    @BindView(R.id.house_intro_layout)
    LinearLayout houseIntroLayout;
    @BindView(R.id.btn_contact_house_owner)
    TextView btnContactHouseOwner;
    @BindView(R.id.btn_reserve_now)
    TextView btnReserveNow;
    @BindView(R.id.bottom_view)
    LinearLayout bottomView;
    @BindView(R.id.tv_comments_count)
    TextView tvCommentsCount;
    @BindView(R.id.star_layout)
    LinearLayout starLayout;
    @BindView(R.id.iv_house_appraiser)
    CircleImageView ivHouseAppraiser;
    @BindView(R.id.tv_appraiser)
    TextView tvAppraiser;
    @BindView(R.id.tv_appraise_time)
    TextView tvAppraiseTime;
    @BindView(R.id.tv_comment_content)
    TextView tvCommentContent;
    @BindView(R.id.comment_imgs_layout)
    LinearLayout commentImgsLayout;
    @BindView(R.id.tv_all_comments)
    TextView tvAllComments;
    @BindView(R.id.house_comments_layout)
    LinearLayout houseCommentsLayout;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.house_location_map)
    MapView houseLocationMap;
    @BindView(R.id.house_location_layout)
    LinearLayout houseLocationLayout;
    @BindView(R.id.tv_house_type)
    TextView tvHouseType;
    @BindView(R.id.tv_house_rooms)
    TextView tvHouseRooms;
    @BindView(R.id.tv_house_toilet)
    TextView tvHouseToilet;
    @BindView(R.id.tv_house_peoples)
    TextView tvHousePeoples;
    @BindView(R.id.tv_checkin_time)
    TextView tvCheckinTime;
    @BindView(R.id.tv_checkout_time)
    TextView tvCheckoutTime;
    @BindView(R.id.tv_goto_calender)
    TextView tvGotoCalender;
    @BindView(R.id.house_detail_layout)
    LinearLayout houseDetailLayout;
    @BindView(R.id.facility_items_layout)
    LinearLayout facilityItemsLayout;
    @BindView(R.id.tv_facility_count)
    TextView tvFacilityCount;
    @BindView(R.id.facility_layout)
    LinearLayout facilityLayout;
    @BindView(R.id.tv_debook_content)
    TextView tvDebookContent;
    @BindView(R.id.debook_layout)
    LinearLayout debookLayout;
    @BindView(R.id.tv_likely_house)
    TextView tvLikelyHouse;
    @BindView(R.id.likely_house_recyclerview)
    RecyclerView likelyHouseRecyclerview;
    //    @BindView(R.id.tv_more_intro)
//    TextView tvMoreIntro;
    @BindView(R.id.expand_text)
    ExpandableTextView expandableText;
    @BindView(R.id.tv_max_room_number)
    TextView tvMaxRoomNumber;
    @BindView(R.id.tv_max_people_number)
    TextView tvMaxPeopleNumber;
    @BindView(R.id.tv_max_bed_number)
    TextView tvMaxBedNumber;

    private List<String> bannerUrls = new ArrayList<>();
    private List<String> bannerTitles = new ArrayList<>();
    private String resourceCode = "";

    private HouseResourceDetailBean houseResourceDetail;
    private boolean isExpandedFlag = true;
    private GeocodeSearch geocoderSearch;
    private AMap aMap;
    private Marker regeoMarker;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_house_resource_detail);
        ButterKnife.bind(this);
        initData();
        initView();
        houseLocationMap.onCreate(savedInstanceState);// 此方法必须重写
        getHouseResourceDetail();

    }

    private void initData() {
        resourceCode = getIntent().getExtras().getString("resourceCode");
    }

    private void initView() {
        tvMidTitle.setText("房源详情");
        ivRight.setVisibility(View.VISIBLE);
        ivRight.setImageResource(R.drawable.ic_share_app);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 450);
        houseImgBanner.setLayoutParams(params);
    }

    @OnClick({R.id.iv_left_back, R.id.iv_right, R.id.iv_collect, R.id.tv_all_comments, R.id.tv_goto_calender,
            R.id.btn_contact_house_owner, R.id.btn_reserve_now, R.id.house_owner_info_layout})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.iv_left_back:
                finish();
                break;
            case R.id.iv_right:
                showToast("分享成功");
                break;
            case R.id.iv_collect:
                if (houseResourceDetail.collection == 1) {
                    dealCollection(false, houseResourceDetail);
                } else {
                    dealCollection(true, houseResourceDetail);
                }
                break;
            case R.id.tv_all_comments:
                break;
            case R.id.tv_goto_calender:
                showDialogFragment();
                break;
            case R.id.btn_contact_house_owner:
                bundle.putSerializable("houseDetail", houseResourceDetail);
                bundle.putInt("btnType", 1);
                AndroidUtils.startNextActivity(HouseResourceDetailActivity.this, ConsultOrBookInfoActivity.class, bundle, false);
                break;
            case R.id.btn_reserve_now:
                bundle.putSerializable("houseDetail", houseResourceDetail);
                bundle.putInt("btnType", 2);
                AndroidUtils.startNextActivity(HouseResourceDetailActivity.this, ConsultOrBookInfoActivity.class, bundle, false);
                break;
            case R.id.house_owner_info_layout:
                AndroidUtils.startNextActivity(HouseResourceDetailActivity.this, LandloadDetailActivity.class, null, false);
                break;
        }
    }

    public void showDialogFragment() {
        FragmentTransaction mFragTransaction = getFragmentManager().beginTransaction();
        Fragment fragment = getFragmentManager().findFragmentByTag("dialogFragment");
        if (fragment != null) {
            //为了不重复显示dialog，在显示对话框之前移除正在显示的对话框
            mFragTransaction.remove(fragment);
        }
        HouseBookInfoFragment bookInfoFragment = HouseBookInfoFragment.newInstance(houseResourceDetail.houseresourcePrice);
        bookInfoFragment.show(mFragTransaction, "bookInfoFragment");
    }

    private void getHouseResourceDetail() {
        JSONObject object = new JSONObject();
        try {
            object.put("resourceId", resourceCode);
            object.put("userId", SPUtils.getStringByKey(this, Constants.UserId));
            String paramJson = object.toString();

            Type type = new TypeToken<LzyResponse<HouseResourceDetailBean>>() {
            }.getType();
            ServerApi.<LzyResponse<HouseResourceDetailBean>>getData(type, Urls.getHouseResourceDetail, "", AESUtil.encrypt(paramJson))//
                    .subscribeOn(Schedulers.io())//
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@NonNull Disposable disposable) throws Exception {
                            showLoading("获取房源详情中...");
                        }
                    })//
                    .map(new Function<LzyResponse<HouseResourceDetailBean>, HouseResourceDetailBean>() {
                        @Override
                        public HouseResourceDetailBean apply(@NonNull LzyResponse<HouseResourceDetailBean> response) throws Exception {
                            return response.data;
                        }
                    })//
                    .observeOn(AndroidSchedulers.mainThread())  //
                    .subscribe(new Observer<HouseResourceDetailBean>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(@NonNull HouseResourceDetailBean bean) {
                            houseResourceDetail = bean;
                            handler.sendEmptyMessage(1);
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            e.printStackTrace();            //请求失败
                            dismissLoading();
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    fillDetailData();
                    break;
            }
        }
    };

    private void fillDetailData() {
        if (null != houseResourceDetail.picList) {
            for (HouseResourceDetailBean.PicListBean picBean : houseResourceDetail.picList) {
                bannerUrls.add(Urls.HouseResourceImageBaseUrl + picBean.resourcePic);
                bannerTitles.add(Constants.RMB_UNIT + houseResourceDetail.resourcePrice);
            }
            initBanner();
        }

        if (!TextUtils.isEmpty(houseResourceDetail.userPic))
            new GlideImageLoader().displayImage(this, Urls.UserImageBaseUrl + houseResourceDetail.userPic, ivHouseOwner);
        else
            new GlideImageLoader().displayImage(this, R.drawable.ic_default_avatar2, ivHouseOwner);

        tvHouseOwner.setText(houseResourceDetail.resourceUserName);
        tvHouseAddress.setText(houseResourceDetail.resourceName);
        tvRentMode.setText(houseResourceDetail.resourceRentaltypeName);
        expandableText.setText(houseResourceDetail.resourceIntroduction);
        tvHouseType.setText(houseResourceDetail.resourceTypeName);

        tvHouseRooms.setText(houseResourceDetail.resourceBedroomNum + "");
        tvHouseToilet.setText(houseResourceDetail.resourceToiletNum + "");
        tvHousePeoples.setText(houseResourceDetail.resourceMaximumNum + "");

        tvMaxRoomNumber.setText(houseResourceDetail.resourceBedroomNum + "个房间");
        tvMaxBedNumber.setText(houseResourceDetail.resourceBedNum + "张床");
        tvMaxPeopleNumber.setText("可住" + houseResourceDetail.resourceMaximumNum + "人");

        if (houseResourceDetail.collection == 1) {
            ivCollect.setImageResource(R.drawable.ic_collected);
        } else {
            ivCollect.setImageResource(R.drawable.ic_uncollect);
        }

        dealComment();

        dealFacilityShow();

        if (!TextUtils.isEmpty(houseResourceDetail.resourceCustomRefundName))
            tvDebookContent.setText(houseResourceDetail.resourceCustomRefundName);
        else
            tvDebookContent.setText("入住前" + houseResourceDetail.resourceCancelDays + "天取消预订，则全额退款；不符合条件，则扣除剩余房款的" + houseResourceDetail.resourceRefundPercentage + "%");
        if (null != houseResourceDetail.location)
            getAddress(new LatLonPoint(houseResourceDetail.location.lat, houseResourceDetail.location.lon));
    }

    /**
     * 配套设施显示
     */
    private void dealFacilityShow() {
        StringBuilder facilityStr = new StringBuilder();
        if (!TextUtils.isEmpty(houseResourceDetail.resourceInfrastructureName))
            facilityStr.append(houseResourceDetail.resourceInfrastructureName);
        if (!TextUtils.isEmpty(houseResourceDetail.resourceresourceAmenitiesName))
            facilityStr.append(houseResourceDetail.resourceresourceAmenitiesName);
        if (!TextUtils.isEmpty(houseResourceDetail.resourceSpecialFacilitiesName))
            facilityStr.append(houseResourceDetail.resourceSpecialFacilitiesName);

        if (!TextUtils.isEmpty(facilityStr)) {
            String[] facilityList = facilityStr.toString().split(",");
            if (null != facilityList && facilityList.length > 0) {
                facilityItemsLayout.removeAllViews();
                int count = facilityList.length > 4 ? 4 : facilityList.length;
                if (facilityList.length > 4) {
                    tvFacilityCount.setVisibility(View.VISIBLE);
                    tvFacilityCount.setText("+" + facilityList.length);
                } else {
                    tvFacilityCount.setVisibility(View.GONE);
                }
                for (int fa = 0; fa < count; fa++) {
                    View facilityView = LayoutInflater.from(this).inflate(R.layout.facility_cell_layout, null, false);
                    TextView tvFacility = (TextView) facilityView.findViewById(R.id.tv_facility_name);
                    ImageView ivFacility = (ImageView) facilityView.findViewById(R.id.iv_facility_logo);
                    tvFacility.setText(facilityList[fa]);
                    ivFacility.setImageResource(R.drawable.ic_facility_logo);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DeYouApplication.mWidth / 6, LinearLayout.LayoutParams.WRAP_CONTENT);
                    facilityView.setLayoutParams(params);
                    facilityItemsLayout.addView(facilityView);
                }
            }
        }
    }

    private void dealComment() {
        starLayout.removeAllViews();
        for (int i = 0; i < 5; i++) {
            ImageView ivStar = new ImageView(this);
            if (i < houseResourceDetail.evaluateStar) {
                ivStar.setImageResource(R.drawable.ic_star_sel);
            } else {
                ivStar.setImageResource(R.drawable.ic_star_nor);
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(44, 60);
            ivStar.setLayoutParams(params);
            ivStar.setPadding(5, 0, 5, 0);
            starLayout.addView(ivStar);
        }
    }

    /**
     * 响应逆地理编码
     */
    public void getAddress(final LatLonPoint latLonPoint) {
        if (aMap == null) {
            aMap = houseLocationMap.getMap();
            regeoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
                    .icon(BitmapDescriptorFactory
                            .defaultMarker(BitmapDescriptorFactory.HUE_RED)));
//            aMap.setOnMarkerClickListener(this);
        }
        geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(this);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,
                GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        geocoderSearch.getFromLocationAsyn(query);// 设置异步逆地理编码请求
    }


    private void initBanner() {
        houseImgBanner.setBannerTitles(bannerTitles);
        //设置banner样式
        houseImgBanner.setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE);
        houseImgBanner.setImageLoader(new GlideImageLoader());
        houseImgBanner.setImages(bannerUrls);
        //设置banner动画效果
        houseImgBanner.setBannerAnimation(Transformer.DepthPage);
        houseImgBanner.setIndicatorGravity(BannerConfig.CENTER);
        houseImgBanner.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {
                tvLocation.setText(result.getRegeocodeAddress().getCity() + " " + result.getRegeocodeAddress().getDistrict() + " " + result.getRegeocodeAddress().getTownship());
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                        AMapUtil.convertToLatLng(new LatLonPoint(houseResourceDetail.location.lat, houseResourceDetail.location.lon)), 15));
                regeoMarker.setPosition(AMapUtil.convertToLatLng(new LatLonPoint(houseResourceDetail.location.lat, houseResourceDetail.location.lon)));
            } else {
                showToast("获取地图失败");
            }
        } else {
            showToast("获取地图失败");
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    private void dealCollection(final boolean isCollection, final HouseResourceDetailBean houseResource) {
        JSONObject object = new JSONObject();
        try {
            if (isCollection) {
                object.put("resourceId", houseResource.resourceId);
                object.put("userId", SPUtils.getStringByKey(HouseResourceDetailActivity.this, Constants.UserId));
                object.put("resourcePic", houseResource.resourceMainPic);
                object.put("resourceName", houseResource.resourceName);
                object.put("resourceRentaltypename", houseResource.resourceRentaltypeName);
                object.put("resourceRegionname", houseResource.resourceCityName);
                object.put("evaluateStar", houseResource.evaluateStar);
                object.put("evaluateNum", houseResource.evaluateNum);
                object.put("userPic", houseResource.userPic);
                object.put("resourcePrice", houseResource.resourcePrice);
            } else {
                object.put("collectionId", houseResource.collectionId);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String paramJson = object.toString();
        ServerApi.getString(isCollection ? Urls.addCollection : Urls.deleteCollection, "", AESUtil.encrypt(paramJson))//
                .subscribeOn(Schedulers.io())//
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        showLoading(isCollection ? "添加收藏请求中..." : "取消收藏请求中...");
                    }
                })//
                .observeOn(AndroidSchedulers.mainThread())  //
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        SimpleResponse resp = new Gson().fromJson(s, SimpleResponse.class);
                        if (null != resp && resp.code == 1) {
                            if (houseResourceDetail.collection == 1) {
                                ivCollect.setImageResource(R.drawable.ic_uncollect);
                                houseResourceDetail.collection = 0;
                            } else {
                                houseResourceDetail.collection = 1;
                                ivCollect.setImageResource(R.drawable.ic_collected);
                            }
                            Toast.makeText(HouseResourceDetailActivity.this, "操作成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(HouseResourceDetailActivity.this, "操作失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        e.printStackTrace();            //请求失败
                        dismissLoading();
                        Toast.makeText(HouseResourceDetailActivity.this, "操作失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        dismissLoading();
                    }
                });
    }
}
